package DB;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Connection;
import java.util.Properties;
/**
 * Deze klasse maakt de verbinding met de database.
 *
 */
public class DBManager {
	private static DBManager uniqueInstance=null;
	private static Connection con = null ;
	private DBManager(){
		if(!dbExists())
		{
			System.err.println("de database bestaat niet....") ;
		}
	}

	public static synchronized DBManager getInstance() {
		if (uniqueInstance==null) {
			uniqueInstance = new DBManager();
		}
		return uniqueInstance;
	}

	/**
	 * Kijkt of er een connectie is.
	 * @return boolean (getConnection() != null)
	 */
	private Boolean dbExists() {		
		return (getConnection() != null);
	}

	/**
	 * Hiermee kan de Connection worden gesloten, zo word blijven geen connecties open staan.
	 */
	public void close() {
		try {
			con.close();
			uniqueInstance=null;
			con=null;
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * De getConnection leest de database.properties en maakt de connectie.
	 * @return Connection
	 */
	public Connection getConnection(){
		if (con == null) {
			Properties props = new Properties();
			try {
				FileInputStream in = new FileInputStream("./files/ciibay.properties");
				props.load(in);
				in.close();
			} catch (IOException e) {
				System.out.println("Properties bestand niet gevonden");
				e.printStackTrace();
			}
			String drivers = props.getProperty("jdbc.drivers");
			if (drivers != null)
				System.setProperty("jdbc.drivers", drivers);
			String url = props.getProperty("jdbc.url");
			String username = props.getProperty("jdbc.username");
			String password = props.getProperty("jdbc.password");
			try {
				con = DriverManager.getConnection(url, username, password);
			} catch (SQLException e) {
				System.out.println("SQL error: " + e.getMessage());
				e.printStackTrace();
			}
		}
		return con;
	}
}
